package Common

import (
	"encoding/base64"
	"encoding/json"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"time"
)

var jwtKey = []byte("a_secret_key")

type Claims struct {
	UserId uint
	App    uint
	jwt.StandardClaims
}

func ReleaseToken(user Admin) (string, error) {
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.ID,
		App:    uint(user.App),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "System",
			Subject:   "Admin Token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	return token, claims, err
}
func RetMsg(code int8, msg string, data gin.H, ctx *gin.Context) {
	if data == nil {
		cMsg, _ := json.Marshal(gin.H{"code": code, "msg": msg})
		ctx.String(200, base64.StdEncoding.EncodeToString(cMsg))
	} else {
		cMsg, _ := json.Marshal(gin.H{"code": code, "msg": msg, "data": data})
		ctx.String(200, base64.StdEncoding.EncodeToString(cMsg))
	}

}
